import type { FC } from "react";
import { Form, Button, Tabs, App } from "antd";
import { useMutation } from "@tanstack/react-query";
import { useApiRequest } from "../../hook/useApiRequest.ts";
import type { FormItemConfigs } from "../../global.ts";
import FormItems from "../FormItems/index.tsx";

export type AuthMode = 'login-only' | 'register-only' | 'login-register';

export interface AuthFormProps {
  // 登录相关配置
  loginSuccessCallback?: (loginResult: any) => void;
  loginApiUrl?: string;
  loginFormConfig?: FormItemConfigs[];
  
  // 注册相关配置
  registerSuccessCallback?: (registerResult: any) => void;
  registerApiUrl?: string;
  registerFormConfig?: FormItemConfigs[];
  
  // 通用配置
  title?: string;
  boxHeight?: string;
  successTip?: {
    login?: string;
    register?: string;
  };
  buttonText?: {
    login?: string;
    register?: string;
  };
  defaultTab?: 'login' | 'register';
  authMode?: AuthMode; // 新增: 认证模式
}

const AuthForm: FC<AuthFormProps> = ({
  // 登录相关配置
  loginSuccessCallback,
  loginApiUrl,
  loginFormConfig,
  
  // 注册相关配置
  registerSuccessCallback,
  registerApiUrl,
  registerFormConfig,
  
  // 通用配置
  title = "欢迎使用",
  boxHeight,
  successTip = {
    login: "登录成功",
    register: "注册成功",
  },
  buttonText = {
    login: "登录",
    register: "注册",
  },
  defaultTab = "login",
  authMode = 'login-register', // 默认显示登录和注册
}) => {
  const [loginForm] = Form.useForm();
  const [registerForm] = Form.useForm();
  const { message } = App.useApp();
  const { request } = useApiRequest();

  // 登录 mutation
  const loginMutation = useMutation({
    mutationFn: async (values: any) => {
      const response = await request({
        url: loginApiUrl!,
        method: "POST",
        data: values,
      });
      if (response?.code === 200 || response?.success) {
        return response?.data;
      }
      throw new Error(response?.message || response?.error || "登录失败");
    },
    onSuccess: (data) => {
      message.success(successTip.login);
      loginSuccessCallback?.(data);
      loginForm.resetFields();
    },
    onError: (error: Error) => {
      message.error(error.message);
    },
  });

  // 注册 mutation
  const registerMutation = useMutation({
    mutationFn: async (values: any) => {
      const response = await request({
        url: registerApiUrl!,
        method: "POST",
        data: values,
      });
      if (response?.code === 200 || response?.success) {
        return response?.data;
      }
      throw new Error(response?.message || response?.error || "注册失败");
    },
    onSuccess: (data) => {
      message.success(successTip.register);
      registerSuccessCallback?.(data);
      registerForm.resetFields();
    },
    onError: (error: Error) => {
      message.error(error.message);
    },
  });

  // 登录提交处理
  const handleLogin = (values: any) => {
    if (loginApiUrl) {
      loginMutation.mutate(values);
    }
  };

  // 注册提交处理
  const handleRegister = (values: any) => {
    if (registerApiUrl) {
      registerMutation.mutate(values);
    }
  };

  // 根据 authMode 构建 items
  const getTabItems = () => {
    const items = [];
    
    // 登录表单
    if (authMode !== 'register-only') {
      items.push({
        key: 'login',
        label: '登录',
        children: (
          <Form
            form={loginForm}
            layout="vertical"
            onFinish={handleLogin}
            style={{ height: boxHeight || "100%" }}
          >
            <FormItems formItemsConfigs={loginFormConfig} />
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loginMutation.isPending}
                style={{ width: "100%", height: "40px" }}
              >
                {loginMutation.isPending ? "登录中..." : buttonText.login}
              </Button>
            </Form.Item>
          </Form>
        ),
      });
    }

    // 注册表单
    if (authMode !== 'login-only') {
      items.push({
        key: 'register',
        label: '注册',
        children: (
          <Form
            form={registerForm}
            layout="vertical"
            onFinish={handleRegister}
            style={{ height: boxHeight || "100%" }}
          >
            <FormItems formItemsConfigs={registerFormConfig} />
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={registerMutation.isPending}
                style={{ width: "100%", height: "40px" }}
              >
                {registerMutation.isPending ? "注册中..." : buttonText.register}
              </Button>
            </Form.Item>
          </Form>
        ),
      });
    }

    return items;
  };

  const tabItems = getTabItems();

  // 如果只有一个表单,直接显示表单而不显示 Tabs
  if (tabItems.length === 1) {
    return (
      <div style={{ width: "100%" }}>
        <span
          style={{
            display: "block",
            fontSize: "24px",
            fontWeight: "bold",
            marginBottom: "20px",
            textAlign: "center",
          }}
        >
          {title}
        </span>
        {tabItems[0].children}
      </div>
    );
  }

  return (
    <div style={{ width: "100%" }}>
      <span
        style={{
          display: "block",
          fontSize: "24px",
          fontWeight: "bold",
          marginBottom: "20px",
          textAlign: "center",
        }}
      >
        {title}
      </span>
      <Tabs
        defaultActiveKey={defaultTab}
        items={tabItems}
        centered
      />
    </div>
  );
};

export default AuthForm; 